/*
 * Changes made by Stephen on 12/20/2013
 * -Fixed getTransactionByCustomerName and getTransactionByDate to return the correct size array.
 * 
 */
package post.dataaccess;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import post.Payment;
import post.ProductCatalog;
import post.Transaction;
import post.TransactionItem;

/**
 *
 * @author Harry
 */
public class TransactionReader {

    private String transactionFile;
    private String[] wholeTransactions;
    private int numTransactions = 0;
    private static int position;
    private ProductCatalog productcatalog;

    public TransactionReader(String transactionFile, ProductCatalog productCatalog) throws IOException {

        this.transactionFile = transactionFile;
        this.productcatalog = productCatalog;
        wholeTransactions = new String[100];
        try {
            this.transactionFile = transactionFile;
            FileReader fr = new FileReader(transactionFile);
            /*location of products.txt file will be passed as the arguement, pls change the location accordingly.*/

            BufferedReader br = new BufferedReader(fr);
            int i = 0;
            String temp = new String();
            while (true) {
                String s = br.readLine();   //Reads the file line by line                    
                if (s == null) //comparison to determine end of file (null)
                {
                    break;
                }
                if (s.equals("###############################################################################################")) {
                    wholeTransactions[i++] = temp;
                    //   System.out.println(temp);
                    temp = "";
                } else {
                    temp += s;
                }
            }
            numTransactions = i;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ProductReader.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public boolean hasMoreTransaction() {

        if (position < numTransactions) {
            return true;
        } else {
            return false;
        }
    }

    public String getNextTransaction() {

        return wholeTransactions[position++];
    }

    public String[] loadAll() {

        return wholeTransactions;
    }

    public void addTransaction(Transaction transaction) throws IOException {
        String newTransaction;
        newTransaction = "Fake Store" + "\t" + "123 Fake Street" + "\n";
        newTransaction += "Customer Name : " + transaction.getCustomerName() + "\t" + "Time of Transaction : " + transaction.getDate() + "\n";
        newTransaction += "----------------------------------------------------------------------------- \n";
        TransactionItem[] itemList = transaction.getTransactionItem();

        newTransaction += "Product UPC \t Quantity \t Unit Price \t Sub-Total\n";
        float total = 0;
        for (int i = 0; i < transaction.getNumTransItems(); i++) {
            newTransaction += itemList[i].getUpc() + " \t\t " + itemList[i].getQuantity() + " \t\t $" + productcatalog.getPriceByUpc(itemList[i].getUpc()) + " \t\t $" + Float.toString(productcatalog.getPriceByUpc(itemList[i].getUpc()) * +itemList[i].getQuantity()) + "\n";
            total += productcatalog.getPriceByUpc(itemList[i].getUpc()) * +itemList[i].getQuantity();
        }
        newTransaction += "----------------------------------------------------------------------------- \n";
        newTransaction += "Total : $" + total + "\n";
        newTransaction += "Paid By : " + transaction.getPaymentMode().toString();
        String payTypeInfo = new String();
        if (transaction.getPaymentMode() == Payment.Cash) {
            payTypeInfo = "\nAmount Tendered: $" + transaction.getPaymentReceived() + " \tChange: " + (transaction.getPaymentReceived() - total);
        }
        if (transaction.getPaymentMode() == Payment.CreditCard) {
            payTypeInfo = "\nCard Number : " + transaction.getCardNum();
        }
        newTransaction += payTypeInfo + "\n";
        newTransaction += "###############################################################################################\n";

        FileWriter fw = new FileWriter(transactionFile, true);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(newTransaction);
        bw.close();
    }

    public String[] getTransactionByDate(Date transDate) throws ParseException {
        String[] result = new String[100];
        int j = 0;
        for (int i = 0; i < numTransactions; i++) {
            int tempIndex = wholeTransactions[i].indexOf("Time of Transaction : ");
            int endIndex = wholeTransactions[i].indexOf("----", tempIndex);
            String date = wholeTransactions[i].substring(tempIndex + 22, endIndex);
            SimpleDateFormat ft = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
            Date logDate = ft.parse(date);
            SimpleDateFormat ft2 = new SimpleDateFormat("MM/dd/yyyy");

            if (ft2.format(logDate).equals(ft2.format(transDate))) {
                result[j++] = wholeTransactions[i];
            }
        }
        if (j != 0) {
            String[] resizedResult = new String[j];
            for (int i = 0; i < j; i++) {
                resizedResult[i] = result[i];
            }
            return resizedResult;
        } else {
            return new String[]{"No transactions for Date : " + transDate.toString()};

        }

    }

    public String[] getTransactionByCustomerName(String customerName) {
        String[] result = new String[100];
        int j = 0;
        for (int i = 0; i < numTransactions; i++) {
            //System.out.println(wholeTransactions[i]);
            int tempIndex = wholeTransactions[i].indexOf("Customer Name : ");
            int endIndex = wholeTransactions[i].indexOf("Time", tempIndex);
            String name = wholeTransactions[i].substring(tempIndex + 16, endIndex);
            name = name.replaceAll("\t", "");
            //System.out.println("#"+name+"#");
            if (name.equals(customerName)) {
                result[j++] = wholeTransactions[i];
//                System.out.println(result[j-1]);
            }
        }
        if (j != 0) {
            String[] resizedResult = new String[j];
            for (int i = 0; i < j; i++) {
                resizedResult[i] = result[i];
            }
            return resizedResult;
        } else {
            return new String[]{"No sales for name :" + customerName};
        }
    }
}